<template>
    <div class="component">
    <Breadcrumb :menulist="['首页','菜单管理']" v-on:changeSolution="changeSolution" :componentType="componentType"></Breadcrumb>

    <el-card class="box-card" shadow="hover">
      <div slot="header" class="tabHeader">
          <el-button class="openComp" type="text" @click="showSelectComp">打开菜单库</el-button>
          <span>
            {{componentSelect}}
          </span>
          <el-button class="addPro" icon="el-icon-circle-plus" type="primary" @click="showAddPro">添加菜单</el-button>
      </div>
      <el-table
            :data="tableData"
            max-height="600"
            line-height="50"
            border
            :header-cell-style='headerStyle'
            style="width: calc(100% - 40px); margin: 0 20px;">
            <!--
              <el-table-column
                prop="functionId"
                label="菜单ID"
                width="100"
                align="center">
            </el-table-column>
            -->
            <el-table-column
                prop="functionCode"
                label="菜单编码"
                width="200"
                align="center">
            </el-table-column>
            <el-table-column
                prop="functionName"
                align="center"
                width="200"
                label="菜单名称">
            </el-table-column>
            <el-table-column
                prop="solutionName"
                align="center"
                width="200"
                label="所属项目">
            </el-table-column>
            <el-table-column
                prop="topSolutionName"
                align="center"
                width="100"
                label="所属产品">
            </el-table-column>
            <el-table-column
                prop="moduleName"
                align="center"
                width="200"
                label="所属模块">
            </el-table-column>
            <el-table-column
                prop="treeCode"
                align="center"
                width="200"
                label="树编码">
            </el-table-column>
            <el-table-column
                prop="functionType"
                align="center"
                width="200"
                label="功能类型">
                <template slot-scope="scope">
                    <span class="percentFont">{{scope.row.functionType.displayName}}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="formName"
                align="center"
                width="200"
                label="关联表单">
            </el-table-column>
            <el-table-column
                prop="syncTime"
                align="center"
                width="100"
                label="同步时间">
            </el-table-column>
            <el-table-column
                prop="icon"
                align="center"
                width="100"
                label="图标">
            </el-table-column>
            <el-table-column
                prop="isSystem"
                align="center"
                width="100"
                label="是否系统">
            </el-table-column>
            <el-table-column
                align="center"
                width="160"
                label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="mini" slot="reference" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

     </el-card>

    <el-drawer
      title="菜单库"
      :visible.sync="showComp"
      direction="ltr"
      :with-header="false"
      size="30%">
      <div class="drawerTitle">选择菜单库</div>
      <el-tree
        :data="treeData"
        node-key="id"
        class="tree"
        v-loading="treeLoading"
        :props="treedefaultProps"
        @node-click="handleNode">
      </el-tree>

    </el-drawer>
 
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加项目解决方案 -->
    <el-dialog :title="dialogTitle"  :visible.sync="dialogFormVisible" width="60%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-col :span="24" v-if="dialogTitle === '删除菜单'">
          <el-form-item v-if="dialogTitle === '删除菜单'" label="删除提示信息">
            <div style="color: #d93a49;">{{deleteCheckContent}}</div>
          </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="关联表单" prop="formName">
                <el-select 
                  clearable
                  autocomplete
                  filterable
                  v-model="form.formName" 
                  placeholder="请选择关联表单"
                  @change="onChangeForms"
                  :disabled="dialogTitle !== '添加菜单'" style="width: 100%;">
                  <el-option
                    v-for="item in formsChooseList"
                    :key="item.formId"
                    :label="item.formName"
                    :value="item.formId"
                    >
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="功能地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入功能地址" disabled></el-input>
            </el-form-item>
            <el-form-item label="菜单编码" prop="formCode">
              <el-input v-model="form.formCode" placeholder="请输入菜单编码" disabled></el-input>
            </el-form-item>
            <el-form-item label="菜单名称" prop="formName">
              <el-input v-model="form.formName" placeholder="请输入菜单名称" disabled></el-input>
            </el-form-item>
            <el-form-item label="图标" prop="iconPath">
              <el-input v-model="form.iconPath" placeholder="请输入图标"></el-input>
            </el-form-item>
            <el-form-item label="是否系统" prop="isSystem">
                <el-radio-group v-model="form.isSystem" :disabled="deleteDisabled">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="树编码"  prop="treeCode">
              <el-input v-model="form.treeCode" placeholder="请输入树编码" disabled></el-input>
            </el-form-item>
            <el-form-item label="功能类型"  prop="functionType">
                <el-select v-model="form.functionType" placeholder="请输入功能类型" disabled style="width: 100%;">
                  <el-option value="0" label="Module"></el-option>
                  <el-option value="1" label="Menu"></el-option>
                  <el-option value="2" label="MenuItem"></el-option>
                  <el-option value="3" label="Buttom"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="父菜单"  prop="parentName">
              <el-input v-model="form.parentName" placeholder="请输入父菜单" disabled></el-input>
            </el-form-item>
            <el-form-item label="所属模块"  prop="moduleId">
              <el-input v-model="form.moduleId" placeholder="请输入所属模块" disabled></el-input>
            </el-form-item>
            <el-form-item label="所属项目"  prop="solutionId">
              <el-input v-model="form.solutionId" placeholder="请输入所属项目" disabled></el-input>
            </el-form-item>
            <el-form-item label="所属产品"  prop="topSolutionId">
              <el-input v-model="form.topSolutionId" placeholder="请输入所属产品" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="dialogTitle === '添加菜单'" @click="handleSave('form')">保 存</el-button>
        <el-button type="primary" v-if="dialogTitle === '编辑菜单'" @click="__handleEdit('form')">保 存</el-button>
        <el-button type="primary" plain v-if="dialogTitle === '添加菜单'" @click="resetForm('form')">清 除</el-button>
        <el-button type="danger" plain v-if="dialogTitle === '删除菜单'" @click="__handleDelete('form')">删 除</el-button>
        <el-button @click="handleCancel('form')">取 消</el-button>
      </div>
    </el-dialog>
    </div>
</template>


<script>

import {request, url} from "@/api/request";
import Breadcrumb from "@/components/Breadcrumb.vue";

export default {
  name: "componentd",
  components: {
    Breadcrumb
  },
  props: {
    componentType: {
        type: Number,
        default: 1,//1组件，2产品
    },
  },
  data() {
    return {
      headerStyle: {
        "line-height": "40px"
      },
      tableData: [],
      formLabelWidth: "100px",
      dialogFormVisible: false,
      form: {
        formName: '',
        formId: '',
        formCode: '',
        url: '',
        functionCode: '',
        functionName: '',
        parentId: '',
        parentName: '',
        moduleId: '',
        moduleName: '',
        solutionId: '',
        solutionName: '',
        topSolutionId: '',
        topSolutionName: '',
        treeCode: '',
        functionType: '',
        functionTypeName: '',
        isSystem: '0',
        iconName: '',
        iconPath: '',
      },
      rules: {
        formName: [
          { required: true, message: '请选择关联表单', trigger: 'change' },
        ],
        // functionName: [
        //   { required: true, message: '请输入菜单名称', trigger: 'change' },
        // ],
      },
      showComp: false,
      treeData: [],
      treedefaultProps: {
        children: 'childs',
        label: 'label'
      },
      componentSelect: '-',
      pageNum: 0,
      pageSize: 10,
      total: 0,
      dialogTitle: '添加菜单',
      deleteDisabled: false,
      deleteCheckContent: "",
      defaultModule: "",  // 默认模块id
      defaultModuleLabel: "",
      defaultModuleCode: "",  //  默认模板code
      formsChooseList: "",  //  表单选择器list
      treeLoading: false, // treee loading
      
    };
  },

  created() {
    if (this.$store.state.solution_global) {
      this.treeLoading = true;
      this.getTreesList();
    }
  },
  methods: {
    // 切换 solution 
    changeSolution() {
      this.treeLoading = true;
      this.getTreesList();
    },
    // 菜单数 tree
    getTreesList() {
      let solutionId = this.$store.state.solution_global.solutionId;
      request(`${url.navigationtree}/${solutionId}`,{
        method:'GET',
        data: {}
      },res=>{
        this.treeLoading = false;
        let newData = res.data.root.childs;
        if (!newData) {
          return false;
        }
        let treedata = [];
        // newData.map((item, i) => {
        //   if (!item.childs) {
        //     return false;
        //   }
        //   item.childs.map((cell, j) => {
        //     cell.disabled = true;
        //     if (cell.navigationType.displayName === 'Component') {
        //       delete cell.childs
        //     }
        //   })
        // })
        let d = this.filterTree(newData);
        this.treeData = d;
        console.log(this.newData)
      })
    },

    // 过滤 tree 数据重新整合
    filterTree(data) {
      if(!data) {
        return false;
      }
      return data.map(item => {
        if (item.childs) {
          this.filterTree(item.childs);
        }
        item.label = `${item.label}（${item.navigationType.displayName}）`
        return item;
      }).filter(item => item);
    },

    // 查询列表
    getMenusList() {
      let moduleId = this.defaultModule;
      let solutionId = this.$store.state.solution_global.solutionId;
      let params = {
        currentPage: this.pageNum,
        rows: this.pageSize,
        solutionId: solutionId
      }
      request(`${url.menusList}/${moduleId}`,{
          method:'GET',
          data: params
      },res=>{
        console.log(res)
        this.tableData = res.data.list;
        this.pageNum = res.data.pageNum;
        // this.pageSize = res.data.pageSize;
        this.total = res.data.total;
      })
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getMenusList();
    },
    
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getMenusList();
    },

    showAddPro() {
      if (this.defaultModule === '') {
        this.$message({
          message: '请先选择一个模块',
          type: 'warning'
        });
        return false;
      }
      this.dialogTitle = '添加菜单';
      this.dialogFormVisible = true;

      if (this.defaultModuleCode != 0) {
        this.form.parentName = this.defaultModuleLabel;
        this.form.parentId = this.defaultModule;
      }


      this.getFormsChoose();
    },

    showSelectComp() {
      this.showComp = true
    },

    handleNode(data, parent) {
      console.log(data.navigationType.displayName);
      if (data.navigationType.displayName === "Module") {
        this.showComp = false;
        this.componentSelect = ""; //  初始化
        this.defaultModule = data.id; //  设置选中的module
        this.defaultModuleLabel = data.label; //  设置选中的module
        this.defaultModuleCode = data.navigationType.code; //  设置选中的module

        this.getTreeNode(parent);
        this.getMenusList();
      } else {
        this.$message({
          message: '请先选择模块',
          type: 'warning'
        });
      }

    },

    //获取当前树节点和其父级节点
    getTreeNode(node){
      if (node.parent) {
          this.componentSelect = `${node.label} ${this.componentSelect ? '>':''} ${this.componentSelect}`;
          this.getTreeNode(node.parent); //递归
      }
    },

    // 获取表单选择器
    getFormsChoose() {
        let solutionId = this.$store.state.solution_global.solutionId;
      request(`${url.formsChoose}/${solutionId}`,{
          method:'GET',
          data: {
            currentPage: 0,
            rows: 10000,
            componentId: '',
            moduleId: ''
          }
        },res=>{
          console.log(res)
          this.formsChooseList = res.data.list;
        })
    },

    onChangeForms(value) {
      let option = this.formsChooseList.find(item => item.formId === value);
      console.log(option)
      this.form.formName = option.formName;
      this.form.formCode = option.formCode;
      this.form.formId = option.formId;
      this.form.url = option.url;
      this.form.moduleId = option.moduleId;
      this.form.moduleName = option.moduleName;
      this.form.solutionId = option.solutionId;
      this.form.solutionName = option.solutionName;
      this.form.topSolutionId = option.topSolutionId;
      this.form.topSolutionName = option.topSolutionName;
      this.form.functionType = String(option.formType.code);
      this.form.functionTypeName = option.formType.displayName;
    },

    // 保存
    handleSave(formName) {
      console.log(this.form)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let parmas = {
            formId: this.form.formId,
            formName: this.form.formName,
            formCode: this.form.formCode,
            functionCode: this.form.formCode,
            functionName: this.form.formName,
            url: this.form.url,
            parentId: this.form.parentId,
            parentName: this.form.parentName,
            moduleId: this.form.moduleId,
            solutionId: this.form.solutionId,
            topSolutionId: this.form.topSolutionId,
            functionType: this.form.functionType,
            functionTypeName: this.form.functionTypeName,
            treeCode: '',
            isSystem: this.form.isSystem,
            iconName: '',
            iconPath: '',
          };
          request(`${url.menus}`,{
              method:'POST',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getMenusList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    handleCancel(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },

    // 编辑
    handleEdit(index, row) {
      console.log(row);
      this.dialogTitle = '编辑菜单';
      this.dialogFormVisible = true;
      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.solutionCode = row.solutionCode;
      this.form.moduleCode = row.moduleCode;
      this.form.componentCode = row.componentCode;
      this.form.componentName = row.componentName;
      this.form.description = row.description;
      this.form.packageName = row.packageName;
      this.form.componentId = row.componentId;

    },

    __handleEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.form)
          let parmas = {
            componentCode: this.form.componentCode,  // 菜单code
            componentName: this.form.componentName,  //  菜单名称
            solutionCode: this.form.solutionCode, //  模块
            solutionId: this.form.solutionId,   //  所属项目Id
            description: this.form.description,  //  描述
            moduleId: this.form.moduleId,
            moduleCode: this.form.moduleCode,
            topSolutionId: this.form.topSolutionId
          };
          console.log(parmas)
          request(`${url.components}/${this.form.componentId}`,{
              method:'PUT',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getMenusList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 删除
    handleDelete (index, row) {
      console.log(row)
      this.dialogTitle = '删除菜单';
      this.deleteDisabled = true;
      this.dialogFormVisible = true;

      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.solutionCode = row.solutionCode;
      this.form.moduleCode = row.moduleCode;
      this.form.componentCode = row.componentCode;
      this.form.componentName = row.componentName;
      this.form.description = row.description;
      this.form.packageName = row.packageName;
      this.form.componentId = row.componentId;
      this.deleteCheck(row.componentId);
      
    },

    // check delete
    deleteCheck(componentId) {
      request(`${url.componentsDeleteCheck}/${componentId}`,{
          method:'GET',
          data: {}
      },res=>{
        this.deleteCheckContent = res.data + res.message;
      })
    },

    //  确认删除 
    __handleDelete () {
      let componentId = this.form.componentId;
      request(`${url.components}/${componentId}`,{
          method:'DELETE',
          data: {}
      },res=>{
          this.dialogFormVisible = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.getMenusList();
          this.$refs.form.resetFields();  // 重置 form表单
      })
    }
  }
};
</script>

<style scoped>
.addPro {
  float: right;
}

.openComp {
  margin-left: 20px;
}

.drawerTitle {
  line-height: 70px;
  font-size: 20px;
  margin-left: 30px;
}

.tree {
  margin-left: 30px;
  
}
</style>
